/***
 * 脚本依赖;
 * common.js
 * ejs.js
 * $,jQuery
 *
 */
(function ($) {
    var $settle = {
        payUseTotal: function (options) {
            var canUseAR = 0, //预付款单付款金额
                useAR = 0, // 本次使用预付款单合计金额
                needCash = 0; // 需现金付款金额
            $('.table-advance-receipt').find('input[type=number]').each(function (index, item) {
                canUseAR = floatTool.add(canUseAR, parseFloat($(item).attr('max')));
                var total_ = floatTool.add(useAR, parseFloat($(item).val()));
                if (total_ > options.payTotal_) { // 支付金额大于应付金额
                    $(item).val(floatTool.subtract(options.payTotal_, useAR));
                    useAR = options.payTotal_;
                } else {
                    useAR = total_;
                }
            });
            if (options.payTotal_ > useAR) {
                needCash = floatTool.subtract(options.payTotal_, useAR);
            }
            $('.can-cash-total').html(needCash);
            $('.ar-pay-total').html(useAR);
            $('.can-use-total-2').html(canUseAR);
            if ($settle.getType(options) == '付') {
                $('.pay-this-time').html(options.payTotal_); // 本次付款金额
            } else {
                $('.pay-this-time').html(useAR); // 本次付款金额
            }

            // debugger;
            // $('.pay-total').html(number_format(total, 2));
            $('.total').html(number_format(useAR, 2));
            options.calcPayTotal(useAR);
//             $('.need-pay-total').html(total/);
        },
        calTotalTips: function (total, canUseTotal, needPayTotal, options) {
            var $tips = $('.modal-title').find('.tips');
            if (!$tips.length) {
                $tips = $('<div class="tips ffs12" style="float: right;margin-right: 15px;font-weight: normal;"></div>');
                $('.modal-title').append($tips);
            }
            $tips.html('选择预' + $settle.getType(options) + '款单合计：' + total +",可使用金额：" + canUseTotal
                + ",需" + $settle.getType(options) + "款金额：" + needPayTotal);
        },
        canUseTotal: function (options, total) {
            $('.can-use-total').html(number_format(total, 2));
        },
        initSelected: function (options, yushoukuan, pays, selected) {
            var html = $.ajax({
                type: 'GET',
                url: 'http://' + getDomain() + '/admin/templets/selected-advance.html', async: false
            });
            $('.table-advance-receipt').replaceWith(ejs.render(html.responseText
                , {
                    yushoukuan: yushoukuan, pays: pays, selected: selected,
                    type: options.type || 0,
                    isCheck: options.check
                }));
            $settle.payUseTotal(options);
            onInput($('.table-advance-receipt input[type=number]'), function () {
                var $max = parseFloat($(this).attr('max'));
                var $val = parseFloat($(this).val());
                if ($val > $max) {
                    $(this).val($max);
                }
                $settle.payUseTotal(options);
            });
            onChange($('.table-advance-receipt').find('input[type=checkbox]:checked'), function () {
                var $data = $(this).data('json');
                delete selected[$data.id];
                $(this).closest('tr').remove();
                $settle.initSelected(options, yushoukuan, pays, selected);
            });

            var checked = $('.table-advance-receipt').find('input[type=checkbox]:checked'), total = 0, canuse = 0,
                usedTotal = 0;
            if (checked.length) {
                checked.each(function (index, item) {
                    options.selected[$(item).data('json').id] = $(item).data('json').id;
                    total = floatTool.add(total, $(item).data('json').totalDeposit);
                    canuse = floatTool.add(canuse, floatTool.subtract($(item).data('json').totalDeposit, $(item).data('json').totalVerified));
                    usedTotal = floatTool.add(usedTotal, $(item).data('json').lockTotal || 0)
                })
            }
        },
        getType: function (options) {
            if (options.type && options.type == '1')return '付';
            return '收';
        },
        init: function (options) {
            var $settle_ = $(this);
            var $pay = $('<input type="button" class="btn btn-primary btn-select" value="选择预' + $settle.getType(options) + '款单" />');
            var $footer = '<table class="table " style="font-size: 10px;margin-top: -1px;"> \
                <tr> \
                <td class="alert-warning">合计： \
                本次' + $settle.getType(options) + '款金额：<span class="cash-label pay-this-time">' + options.payTotal_ + '</span>元, \
                预' + $settle.getType(options) + '款合计可使用金额：<span class="can-use-total can-use-total-2 cash-label">0.00</span>元, \
                预' + $settle.getType(options) + '款付款金额：<span class="can-use-total ar-pay-total cash-label">0.00</span><span ' + ($settle.getType(options) == '收' ? 'style="display:none;"' : '') + ' >元, \
                现金付款金额：<span class="can-cash-total cash-label">' + options.payTotal_ + '</span>元</span>.\
                </tr> \
                </table>';
            if (!options.check) {
                debugger;
                $settle_.append($pay);
                onClick($pay, function () {
                    var html = $.ajax({
                        type: 'GET',
                        url: 'http://' + getDomain() + '/admin/templets/select-advance.html', async: false
                    });
                    $.when(getDataByUrl(options.payType, 'payType'), $.get(options.queryAdvanceReceipt))
                        .then(function (res1, res) {
                            // $('.pay-method').html(ejs.render($('#pays-template').html(), {pays: res}))
                            function getSelected() {
                                var total = 0, usedTotal = 0;
                                var checked = $('.modal-body input[type=checkbox]:checked');
                                if (checked.length) {
                                    checked.each(function (index, item) {
                                        options.selected[$(item).data('json').id] = $(item).data('json').id;
                                        total = floatTool.add($(item).data('json').totalDeposit, total);
                                        usedTotal = floatTool.add($(item).data('json').totalVerified, usedTotal);
                                    })
                                }
                                //options.selected
                                return {
                                    canUse: floatTool.subtract(total, usedTotal),
                                    total: total
                                }
                            }

                            _alert({
                                title: '选择预' + $settle.getType(options) + '款单',
                                width: 'large',
                                hasfoot: true,
                                body: ejs.render(html.responseText, {
                                    yushoukuan: res[0].list,
                                    pays: res1,
                                    type: options.type || 0,
                                    selected: options.selected
                                }),
                                shown: function () {
                                    //$settle.calTotalTips(0, 0, options.payTotal_, options);
                                    var selected = getSelected();
                                    $settle.calTotalTips(selected.total, selected.canUse, options.payTotal_, options);
                                    onChange($('.modal-body input[type=checkbox]'), function () {
                                        if ($(this).is(':checked')) {
                                            // 预售款单
                                            var selected = getSelected();
                                            $settle.calTotalTips(selected.total, selected.canUse, options.payTotal_, options);
                                            return false; //
                                        }
                                    })
                                },
                                okHide: function () {
                                    // var checked = $('.modal-body input[type=checkbox]:checked');
                                    // if (checked.length) {
                                    //     checked.each(function (index, item) {
                                    //         options.selected[$(item).data('json').id] = $(item).data('json').id;
                                    //     })
                                    // }
                                    getSelected();
                                    $settle.initSelected(options, res[0].list, res1, options.selected);
                                }
                            })
                        })
                        .fail(function (e) {
                            fnFail(e)
                        });


                });
                if (_.valueOf(options.selected).length) {
                    getDataByUrl(options.payType, 'payType')
                        .then(function (res) {
                            $settle.initSelected(options, _.values(options.selected), res, options.selected);
                        })
                }
            } else if (options.check) {
                $.when(getDataByUrl(options.payType, 'payType'), $.get(options.queryAdvanceReceipt))
                    .then(function (res1, res) {
                        res[0].list.map(function (item) {
                            options.selected['' + item.id] = item;
                            return item;
                        });
                        $settle.initSelected(options, res[0].list, res1, options.selected);
                    })
                    .fail(function (e) {
                        console.log(e);
                    })

            }
            $settle_.prepend($footer);
            $settle_.prepend($('<table class="table-advance-receipt"></table>'));
            options.rendered && options.rendered();
        },
    };
    $.fn.settle = function (options) {

        var _default = {
            fields: []
            // 'location': 'top',
            // 'background-color': 'blue'
        };
        options = $.extend({selected: {}}, _default, options || {});
        // if (!$.isArray(options.fields) || !options.fields.length) {
        //     throw new Error('option.field must be array and option.field.length must over 0 !')
        // }
        return this.each(function () {
            $settle.init.call(this, options);
        })
    };
})(jQuery);
